'''
请求体
'''
from typing import Union, Set, List

from fastapi import APIRouter, Path, Body
from pydantic import BaseModel, Field

router = APIRouter()


#  请求体必须继承 BaseModel
#  Field数据校验
class Item(BaseModel):
    name: str = Field(default="Foo", max_length=50, min_length=3)
    desc: Union[str, None] = Field(default=None, description="描述")
    price: float
    tax: Union[float, None] = None
    tags: Set[str] = set()
    loves:List[str] = []
    class Config:
        json_schema_extra = {
            "example": {
                "name": "Foo",
                "description": "A very nice Item",
                "price": 35.4,
                "tax": 3.2,
            }
        }


# 错误示例
@router.get("/body/get_create_item", tags=["请求体参数"])
async def get_create_item(item: Item):
    return item


@router.post("/body/post_create_item", tags=["请求体参数"])
async def post_create_item(item: Item):
    return item


# 同时声明请求体、路径参数和查询参数
@router.put("/body/items/{item_id}", tags=["请求体参数"])
async def create_item(item_id: int, item: Item, query: Union[str, None] = None):
    result = {"item_id": item_id, **item.dict()}
    if query:
        result.update({"query": query})
    return result


@router.put("/body/items/{item_id}", tags=["请求体参数"])
async def update_item(*, item_id: int = Path(title="The ID of the item to get", ge=0, le=1000),
                      q: Union[str, None] = None, item: Union[Item, None] = Body(default=None,description="请求体参数"), ):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    if item:
        results.update({"item": item})
    return results
